﻿<template>
  <a-drawer
    :destroyOnClose="true"
    :title="title"
    :visible="visible"
    width="90%"
    @close="() => { this.visible = false }">
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="客户名称" prop="CustomerName">
            <CustRemoteSearchByCondition
              v-model="entity.CustomerId"
              :disabled="disabled"
              :is-my-data="true"
              mode="default"
              placeholder="检索客户(名称/编号)(省市区名称禁止查询)"
              @BindCustomer="BindCustomer">
            </CustRemoteSearchByCondition>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="客户经理" prop="AccountManager">
            <a-input v-model="entity.AccountManager" autocomplete="off" disabled placeholder="客户经理"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="单据号" prop="DocumentNo">
            <a-input v-model="entity.DocumentNo" autocomplete="off" disabled placeholder="系统自动生成"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="核算结束时间" prop="AccountingEndDate">
            <a-date-picker
              v-model="entity.AccountingEndDate"
              :disabled="disabled"
              format="YYYY-MM-DD"
              style="width: 100%"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="经办人" prop="Transactor">
            <a-select v-model="entity.Transactor" :disabled="disabled" placeholder="请选择">
              <a-select-option v-for="item in userList" :key="item.Id" :value="item.Id">
                {{ item.RealName }}
              </a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="组织机构" prop="Department">
            <a-input v-model="entity.Department" :disabled="disabled" autocomplete="off" placeholder="组织机构"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="申请时间" prop="ApplyDate">
            <a-date-picker v-model="entity.ApplyDate" :disabled="disabled" format="YYYY-MM-DD" style="width: 100%"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remark">
            <a-textarea v-model="entity.Remark" :disabled="disabled" autocomplete="off"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item v-if="openType === 3 || openType === 4 || openType === 5" label="审核日期">
            <a-date-picker v-model="entity.ApprovalDate" :disabled="openType === 5" format="YYYY-MM-DD" style="width: 100%"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item v-if="openType === 3 || openType == 4 || openType === 5" label="审批意见" prop="ApprovalComments">
            <a-input v-model="entity.ApprovalComments" :disabled="openType === 5" autocomplete="off"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <PriceChoose ref="materialChoose" @onChoose="handleChoose"></PriceChoose>
      <Detailed ref="Detailed" @onDetail="onDetail"/>
      <a-tabs :active-key="activeKey" @change="tabChange">
        <a-tab-pane key="1" tab="选择数据">
          <div v-if="!disabled" class="itemButton">
            <a-button v-if="openType === 1 || openType === 2 || openType === 4" :disabled="hasCustAndDate()" :loading="loading" icon="transaction" type="primary" @click="addTable">加载明细</a-button>
            <a-button
              :disabled="!hasSelected()"
              :loading="loading"
              icon="minus"
              type="primary"
              @click="handleDelete('',[],selectedRows)">删除
            </a-button>
            <a-button :disabled="this.data.length===0" :loading="loading" icon="delete" type="danger" @click="clearAll"> 全部清空</a-button>
          </div>
          <a-table
            ref="table"
            :bordered="true"
            :columns="columns"
            :dataSource="data"
            :loading="loading"
            :pagination="pagination"
            :rowKey="(row,index) => row.Id||index"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'checkbox' }"
            :scroll="{ y: tableHeight }"
            size="small"
            @change="handleTableChange">
            <span slot="dDate" slot-scope="dDate">{{ timeFormat(dDate, 'YYYY-MM-DD') }}</span>
            <span slot="iQuantity" slot-scope="iQuantity" v-format="'#,##0'">{{ iQuantity }}</span>
            <span slot="ShouldQuantity" slot-scope="ShouldQuantity" v-format="'#,##0'">{{ ShouldQuantity }}</span>
            <span slot="ReturnedQty" slot-scope="ReturnedQty" v-format="'#,##0'">{{ ReturnedQty }}</span>
            <span slot="returningQty" slot-scope="returningQty" v-format="'#,##0'">{{ returningQty }}</span>
            <template slot="cInvCode" slot-scope="text, record">
              <span>{{ record.cInvCode }}/{{ record.cInvName }}</span>
            </template>
            <template slot="GiftPId" slot-scope="text, record">
              <span v-if="record.GiftPId">{{ record.GiftPId }}/{{ record.GiftInvName }}</span>
            </template>
            <template slot="returningQty" slot-scope="text, record, index">
              <a-input-number
                v-model="record.returningQty"
                :disabled="disabled"
                :max="getMaxNumber(record)"
                :min="1"
                size="small"
                style="width: 100%;"
                @change="((value)=>{handleReturningQty(value, record, index)})">
              </a-input-number>
            </template>
            <template slot="action" slot-scope="text, record, index">
              <a :disabled="disabled" @click="handleDelete(index, [record.Id],[record])">删除</a>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" force-render tab="返料汇总">
          <a-table
            ref="table"
            :bordered="true"
            :columns="columnsCopy"
            :dataSource="dataArr"
            :loading="loading"
            :pagination="false"
            :rowKey="(row, index) => index"
            :scroll="{ y: 530 }"
            size="small"
            @change="handleTableChange">
            <span slot="iQuantity" slot-scope="iQuantity" v-format="'#,##0'">{{ iQuantity }}</span>
            <span slot="ShouldQuantity" slot-scope="ShouldQuantity" v-format="'#,##0'">{{ ShouldQuantity }}</span>
            <span slot="ReturnedQty" slot-scope="ReturnedQty" v-format="'#,##0'">{{ ReturnedQty }}</span>
            <span slot="returningQty" slot-scope="returningQty" v-format="'#,##0'">{{ returningQty }}</span>
            <template slot="cInvCode" slot-scope="text, record">
              <span>{{ record.cInvCode }}/{{ record.cInvName }}</span>
            </template>
            <template slot="GiftPId" slot-scope="text, record">
              <span v-if="record.GiftPId">{{ record.GiftPId }}/{{ record.GiftInvName }}</span>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
      <div style="height:50px"></div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '5px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }">
        <a-button @click="close">取消</a-button>&nbsp;
        <a-button v-if="openType !== 3 && openType !== 5" :loading="loading" type="primary" @click="handleSubmit">保存</a-button>
        <a-button v-if="openType === 3" :loading="loading" type="primary" @click="Approve">通过</a-button>&nbsp;&nbsp;
        <a-button v-if="openType === 3" :loading="loading" type="danger" @click="TurnDown">驳回</a-button>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>
import CustRemoteSearchByCondition from '@/components/RemoteSearch/CustRemoteSearchByCondition'
import PriceChoose from '@/components/PriceChoose/MaterialApply.vue'
import moment from 'moment'
import Detailed from './Detailed.vue'
import OperatorCache from '@/utils/cache/OperatorCache'
// 明细
const columns = [
  {
    title: '销售出库',
    children: [
      { title: '单据日期', dataIndex: 'dDate', align: 'center', scopedSlots: { customRender: 'dDate' } },
      { title: '销售发货单号', dataIndex: 'cCode', align: 'center' },
      { title: '销售品名', dataIndex: 'cInvCode', align: 'center', scopedSlots: { customRender: 'cInvCode' }, width: '250px' },
      { title: '发货数量', dataIndex: 'iQuantity', align: 'right', width: '5%', scopedSlots: { customRender: 'iQuantity' } }
    ]
  },
  {
    title: '返料',
    children: [
      { title: '返料规则名称', dataIndex: 'RuleName', align: 'left', width: '250px' },
      { title: '返料品名', dataIndex: 'GiftPId', align: 'center', scopedSlots: { customRender: 'GiftPId' }, width: '250px' },
      { title: '应返', dataIndex: 'ShouldQuantity', align: 'center', scopedSlots: { customRender: 'ShouldQuantity' } },
      { title: '已返', dataIndex: 'ReturnedQty', align: 'center', scopedSlots: { customRender: 'ReturnedQty' } },
      { title: '本次返料', dataIndex: 'returningQty', align: 'center', scopedSlots: { customRender: 'returningQty' } }
    ]
  },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]
// 汇总
const columnsCopy = [
  {
    title: '销售发货',
    children: [
      { title: '销售品名', dataIndex: 'cInvCode', scopedSlots: { customRender: 'cInvCode' } },
      { title: '销售发货数量', dataIndex: 'iQuantity', align: 'center', scopedSlots: { customRender: 'iQuantity' } }
    ]
  },
  {
    title: '返料',
    children: [
      { title: '返料品名', dataIndex: 'GiftPId', scopedSlots: { customRender: 'GiftPId' }, align: 'center' },
      { title: '应返', dataIndex: 'ShouldQuantity', scopedSlots: { customRender: 'ReturnedQty' }, align: 'center' },
      { title: '已返', dataIndex: 'ReturnedQty', scopedSlots: { customRender: 'ReturnedQty' }, align: 'center' },
      { title: '本次返料', dataIndex: 'returningQty', scopedSlots: { customRender: 'returningQty' }, align: 'center' }
    ]
  }
]

export default {
  props: {
    parentObj: Object,
    disabled: { type: Boolean, required: false }
  },
  mounted () {
    this.getUserList()
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true)
    })
  },
  data () {
    return {
      tableHeight: 530,
      Qty: 0,
      a: 0,
      activeKey: '1',
      columns,
      data: [],
      dataArr: [],
      originalData: [],
      userList: [],
      columnsCopy,
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      cc: false,
      filters: {},
      sorter: { field: 'cInvCode', order: 'desc' },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
      loading: false,
      entity: {},
      rules: {
        CustomerName: [{ required: true, message: '未输入', trigger: 'blur' }],
        AccountingEndDate: [{ required: true, message: '未输入', trigger: 'change' }]
      },
      openType: 0, // 0.默认  1.新建 2.编辑  3.审核  4.修改 5.查看
      title: '',
      Id: ''
    }
  },
  components: {
    CustRemoteSearchByCondition,
    PriceChoose,
    Detailed
  },
  methods: {
    tabChange (key) {
      this.activeKey = key
      this.calcDataArr()
    },
    // 选中客户
    BindCustomer (val) {
      this.$set(this.entity, 'CustomerId', val == null ? null : val.Id)
      this.$set(this.entity, 'CustomerName', val == null ? null : val.cCusName)
      this.$set(this.entity, 'AccountManager', val == null ? null : val.PrincipalName)
    },
    onDetail (a) {
      a.forEach(item => {
        // 用于提交编辑保存的值
        this.data.push({
          AutoID: item.AutoID,
          cSOCode: item.cSOCode,
          GiftInvName: item.GiftInvName,
          GiftPId: item.GiftPId,
          dDate: item.dDate,
          cCode: item.cCode,
          cInvCode: item.cInvCode,
          cInvName: item.cInvName,
          iQuantity: Math.round(item.iQuantity),
          RuleName: item.RuleName,
          ShouldQuantity: Math.round(item.ShouldQuantity),
          ReturnedQty: Math.round(item.ReturnedQty),
          returningQty: Math.round(item.NotiQuantity),
          SalePQuantity: Math.round(item.SalePQuantity),
          GiftPQuantity: Math.round(item.GiftPQuantity)
        })
        // 用于对比编辑的原数据
        this.originalData.push({
          AutoID: item.AutoID,
          cSOCode: item.cSOCode,
          GiftInvName: item.GiftInvName,
          GiftPId: item.GiftPId,
          dDate: item.dDate,
          cCode: item.cCode,
          cInvCode: item.cInvCode,
          cInvName: item.cInvName,
          iQuantity: Math.round(item.iQuantity),
          RuleName: item.RuleName,
          ShouldQuantity: Math.round(item.ShouldQuantity),
          ReturnedQty: Math.round(item.ReturnedQty),
          returningQty: Math.round(item.NotiQuantity),
          SalePQuantity: Math.round(item.SalePQuantity),
          GiftPQuantity: Math.round(item.GiftPQuantity)
        })
      })
    },
    calcDataArr () {
      const obj = {}
      this.data.forEach(item => {
        if (!obj[item.cInvName]) {
          obj[item.cInvName] = { ...item }
        } else {
          obj[item.cInvName].iQuantity = (obj[item.cInvName].iQuantity * 1 + Number(item.iQuantity))
          obj[item.cInvName].ShouldQuantity = (obj[item.cInvName].ShouldQuantity * 1 + Number(item.ShouldQuantity))
          obj[item.cInvName].ReturnedQty = (obj[item.cInvName].ReturnedQty * 1 + Number(item.ReturnedQty))
          obj[item.cInvName].returningQty = (obj[item.cInvName].returningQty * 1 + Number(item.returningQty))
        }
      })
      if (!this.Id) {
        this.dataArr = []
        for (const [index, value] of Object.entries(obj)) {
          this.dataArr.push({
            cInvCode: value.cInvCode,
            cInvName: value.cInvName,
            iQuantity: value.iQuantity,
            GiftPId: value.GiftPId,
            GiftInvName: value.GiftInvName,
            ShouldQuantity: value.ShouldQuantity,
            ReturnedQty: value.ReturnedQty,
            returningQty: value.returningQty,
            SalePQuantity: value.SalePQuantity,
            GiftPQuantity: value.GiftPQuantity
          })
        }
      } else {
        for (const [index, value] of Object.entries(obj)) {
          this.dataArr.forEach(item => {
            if (item.cInvName === value.cInvName) {
              item.ReturnedQty = value.ReturnedQty
              item.returningQty = value.returningQty
            }
          })
        }
      }
    },
    handleChoose (a) {
      const ar = []
      this.data.forEach(item => {
        a.forEach((val, i) => {
          if (item.ProductId === val.cInvCode) {
            ar.push(val)
            a.splice(i, 1)
          }
        })
      })
      if (ar.length === 0) {
        a.forEach(item => {
          this.data.push({
            ProductId: item.cInvCode,
            ProductName: item.cInvName,
            cInvCode: item.cInvCode,
            cInvStd: item.cInvStd
          })
        })
      } else {
        this.$message.error('重复产品已筛选掉')
        a.forEach(item => {
          const aa = {
            ProductId: item.cInvCode,
            ProductName: item.cInvName,
            cInvCode: item.cInvCode,
            cInvStd: item.cInvStd
          }
          this.data = [...this.data, aa]
        })
      }
    },
    close () {
      this.visible = false
      this.entity = {}
    },
    // 添加按钮
    addTable () {
      if (this.entity.CustomerName && this.entity.AccountingEndDate) {
        // 明细
        this.$refs.Detailed.openForm(this.entity, this.data)
      } else {
        this.$message.error('请先选择客户和日期')
      }
    },
    handleReturningQty (value, record, index) {
      const returningQty = Number(record.ShouldQuantity) - Number(record.ReturnedQty)
      if (value > returningQty) {
        this.$set(this.data[index], 'returningQty', returningQty)
      }
    },
    // 获取选中的行
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    // 删除子表数据
    handleDelete (index, ids, rows) {
      if (this.openType === 2) {
        if (ids.length === 0 && rows.length > 0) {
        } else if (ids.length === 1 && rows.length === 1 && ids[0] === undefined) {
          this.data.splice(index, 1)
        } else {
          this.$confirm({
            title: '确认删除吗?',
            onOk: () => {
              this.$http.post('/GiftManagement/GMM_GiftMaterialApplyDetails/DeleteData', ids).then(res => {
                if (res.Success) {
                  this.data.splice(index, 1)
                  this.originalData.splice(index, 1)
                  this.calcDataArr()
                  this.pagination.total = this.data.length
                  this.$message.success('删除成功')
                } else {
                  this.$message.error(res.Msg)
                }
              })
            }
          })
        }
      } else {
        this.originalData.splice(index, 1)
        this.data.splice(index, 1)
        this.calcDataArr()
      }
    },
    // 清空所有子表数据
    clearAll () {
      const that = this
      this.loading = true
      this.$confirm({
        title: '是否清空全部返料明细记录?',
        onOk: () => {
          that.$http.post('/GiftManagement/GMM_GiftMaterialApplyMain/DeleteSubtable', [{
            Condition: 'ParentId',
            Keyword: that.entity.Id
          }]).then(res => {
            if (res.Success) {
              that.data = []
              that.dataArr = []
              that.originalData = []
              that.pagination.total = that.data.length
              that.$message.success('清空成功')
              that.loading = false
            } else {
              that.$message.error(res.Msg)
              that.loading = false
            }
          })
        },
        onCancel: () => {
          that.loading = false
        }
      })
    },
    hasCustAndDate () {
      if (this.entity.CustomerId == undefined || this.entity.CustomerId == null || this.entity.AccountingEndDate == undefined || this.entity.AccountingEndDate == null) {
        return true
      }
      return false
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    op () {
      return OperatorCache.info
    },
    getUserList () {
      this.$http.post('/Base_Manage/Base_User/GetDataList', {}).then(resJson => {
        this.userList = resJson.Data
      })
    },
    init () {
      this.visible = true
      this.Id = ''
      this.entity = {}
      this.data = []
      this.dataArr = []
      this.originalData = []
      this.activeKey = '1'
      this.entity.ApplyDate = moment(new Date())
      this.entity.ApprovalDate = moment(new Date())
      this.$set(this.entity, 'Transactor', this.op().Id)
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 选中的当前行
    RuleName (a) {
      this.$set(this.entity, 'RuleMainName', a[0].RuleName)
      this.$set(this.entity, 'RuleMainId', a[0].Id)
    },
    getDataListss () {
      this.$http
        .post('/GiftManagement/GMM_GiftMaterialApplyMain/GetTheData', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Id',
          SortType: 'desc',
          Search: {
            Condition: 'Id',
            Keyword: this.Id
          }
        })
        .then(res => {
          this.loading = false
          if (res.Success) {
            this.entity = res.Data
            this.data = res.Data.GMM_GiftMaterialApplyDetailsList
            if (res.Data.Total) {
              const pagination = { ...this.pagination }
              pagination.total = res.Data.Total
              this.pagination = pagination
            }
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    getMaxNumber (record) {
      return Number(record.getMaxNumber) - Number(record.ReturnedQty)
    },
    openForm (id, title, openType) {
      this.init()
      this.title = title
      this.openType = openType
      if (id) {
        this.Id = id
        this.$http
          .post('/GiftManagement/GMM_GiftMaterialApplyMain/GetTheData', {
            id: this.Id
          })
          .then(res => {
            this.loading = false
            if (res.Success) {
              this.entity = res.Data
              if (this.entity['AccountingStartDate']) {
                this.entity['AccountingStartDate'] = moment(this.entity['AccountingStartDate'])
              }
              if (this.entity['AccountingEndDate']) {
                this.entity['AccountingEndDate'] = moment(this.entity['AccountingEndDate'])
              }
              if (this.entity['ApplyDate']) {
                this.entity['ApplyDate'] = moment(this.entity['ApplyDate'])
              }
              if (this.entity['ApprovalDate']) {
                this.entity['ApprovalDate'] = moment(this.entity['ApprovalDate'])
              }
              this.data = res.Data.GMM_GiftMaterialApplyDetailsList
              this.dataArr = res.Data.GMM_GiftMaterialApplyDetailsTotalList
            } else {
              this.$message.error(res.Msg)
            }
          })
      }
    },
    // 审批驳回
    TurnDown () {
      this.entity.ApprovalStatus = 2
      const entityData = this.entity
      entityData.GMM_GiftMaterialApplyDetailsList = [...this.data]
      this.$http.post('/GiftManagement/GMM_GiftMaterialApplyMain/SaveData', entityData).then(resJson => {
        this.loading = false
        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.visible = false
          this.parentObj.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    // 审批通过
    Approve () {
      this.entity.ApprovalStatus = 1
      const entityData = this.entity
      entityData.GMM_GiftMaterialApplyDetailsList = [...this.data]
      this.$http.post('/GiftManagement/GMM_GiftMaterialApplyMain/SaveData', entityData).then(resJson => {
        this.loading = false
        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.visible = false
          this.parentObj.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    // 保存
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        if (this.data.length === 0) {
          this.$message.warning('此客户没有添加返料明细数据')
          return
        }
        if (this.title === '修改') this.entity.ApprovalStatus = null
        const entityData = this.entity
        if (this.data.length > 0) {
          this.data.forEach(val => {
            val.returningQty = Number(val.returningQty)
          })
        }
        this.calcDataArr()
        entityData.GMM_GiftMaterialApplyDetailsList = [...this.data]
        entityData.GMM_GiftMaterialApplyDetailsTotalList = [...this.dataArr]
        this.$http.post('/GiftManagement/GMM_GiftMaterialApplyMain/SaveData', entityData).then(resJson => {
          this.loading = false
          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false
            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.itemButton {
  width: 100%;
  border-style: solid;
  border-width: 1px 1px 0 1px;
  border-color: #E8E8E8;
  border-radius: 10px 10px 0 0;
  padding: 20px 10px;
  background: #fff;
  text-align: left;
  z-index: 1;

  button {
    margin: 0 5px;
  }
}

</style>
